# coding:utf-8
# @Time : 2021/5/8 11:35 
# @Author : minuy
# @File : media.py
import os
from datetime import datetime

from flask import abort, send_file, request
from werkzeug.utils import secure_filename

from app.libs.file_tool import get_file_url
from app.web import web

# 受支持的文件类型
support_format = ['jpg', 'png', 'gif', 'jpeg']
# 文件的最大大小（6M）
max_file_size = 6000000


@web.route('/file/<filename>')
def get_file(filename=None):
    """
    获取media文件夹内的文件并返回
    :param filename: 文件名
    :return: 文件对象
    """
    if filename:
        path_root = os.getcwd()  # D:\Project\fifthplaymate\FifthPlaymateServer
        path_media = os.path.join(path_root, 'media')
        if os.path.exists(path_media) and os.path.isdir(path_media):  # 判断是否是文件夹
            path_file = os.path.join(path_media, filename)
            if os.path.isfile(path_file) and os.path.exists(path_file):  # 判断文件是否存在
                suffix = os.path.splitext(path_file)[1].replace('.','')
                print('文件后缀：', suffix)
                if suffix in support_format:
                    file_size = os.path.getsize(path_file)
                    if max_file_size >= file_size:
                        print('返回文件：', path_file)
                        return send_file(path_file)
                    else:
                        print('文件错误，所请求的文件太大！', file_size)
                        abort(413)
                else:
                    print('文件错误，不支持的类型！')
                    abort(403)
            else:
                print('系统错误，文件不存在！')
                abort(404)
        else:
            print('系统错误，media应该是文件夹！')
            abort(500)

        print(filename)
        print(path_root)
        print(path_media)
        print(path_file)
    return 'error'


@web.route('/upload_file', methods=['POST', 'GET'])
def up_file():
    """
    上传图片文件到media文件夹
    :return:
    """
    if request.method == 'POST':
        f = request.files['file']
        if f:
            path_root = os.getcwd()  # D:\Project\fifthplaymate\FifthPlaymateServer
            path_media = os.path.join(path_root, 'media')
            if os.path.exists(path_media) and os.path.isdir(path_media):  # 判断是否是文件夹
                file_name = secure_filename(f.filename)
                path_file = os.path.join(path_media, file_name)
                suffix = os.path.splitext(path_file)[1].replace('.', '')  # 获取文件名后缀

                # 重命名
                if not suffix:
                    path_file = path_file + '.jpg'
                    suffix = os.path.splitext(path_file)[1].replace('.', '')  # 获取文件名后缀

                file_name = datetime.now().strftime('%Y%m%d%H%M%S') + 'F' + str((int(datetime.now().timestamp() * 1000))%1000)
                file_name = file_name + '.' + suffix
                path_file = os.path.join(path_media, file_name)

                if suffix in support_format:
                    f.save(path_file)
                    print('文件保存成功', path_file)
                    return get_file_url(file_name)
                else:
                    print('文件类型不受支持', suffix)
                    abort(403)
            else:
                print('文件夹不存在')
                abort(500)
        else:
            print('没有上传文件')
            abort(403)
    return '请使用POST方法'

